package com.itlong.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceAuthFileDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListAuthFileConsumeRecordsDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListAuthRulesDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListDTO;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.PO.RoomInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.DeviceAuthFileVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListAuthRulesVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.CloudDeviceErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudTalkPushCloudIntercomChangeLogServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthFileConsumeRecordsServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthFileServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListAuthRulesServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListServiceClient;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.iottp.IIotTpJPushClientServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppPadFaceServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 * 云对讲设备接口控制器
 * </desc>
 *
 * @createDate 2017-11-15.
 */
@RestController
@RequestMapping("/smartCommunity/interface")
@RefreshScope
public class CloudTalkController {
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkController.class);

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;
    //极光推送
    @Autowired
    IIotTpJPushClientServiceClient iIotTpJPushClientServiceClient;
    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;
    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;
    @Autowired
    IAppPadFaceServiceClient iAppPadFaceServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthFileConsumeRecordsServiceClient authFileConsumeRecordsServiceClient;

    @Autowired
    IOperateDeviceWhiteListServiceClient deviceWhiteListServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthRulesServiceClient iOperateDeviceWhiteListAuthRulesServiceClient;

    @Autowired
    IOperateDeviceWhiteListAuthFileServiceClient iOperateDeviceWhiteListAuthFileServiceClient;

    @Autowired
    ICloudTalkPushCloudIntercomChangeLogServiceClient changeLogServiceClient;

    @Autowired
    IPropertyEquipServiceClient equipServiceClient;

    @Value("${" + PlatformConstants.H5_PAYMENT_HTML + "}")
    public String H5_PAYMENT_HTML;


    /**
     * <desc>
     *      获取设备业务服务器地址
     * <desc/>
     *
     * @param sn 设备序列号
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    /*@RequestMapping(value = "/device/getDeviceServer", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO getDeviceServer(String sn){
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            ProjectPO project = iOperateProjectServiceClient.getOneProject(StringHandlerUtil.getProjectIdBySn(sn));
            if (project == null){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PROJECT_NOT_EXIST.getErrorCode());
            }
            //返回业务服务器地址
            Map<String, Object> map = new HashMap<>();
            map.put("businessServer", project.getDeviceAddress());

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】获取业务服务器地址失败", e);
        }
    }*/

    /**
     * <desc>
     *      设备登录认证
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-15
     */
    //@LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_DEVICE_LOGIN)
    /*@RequestMapping(value = "/device/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO login(String sn){
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            //判断项目状态
            Integer status = iOperateProjectServiceClient.getProjectStatus(StringHandlerUtil.getProjectIdBySn(sn));
            if (null == status){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PROJECT_NOT_EXIST.getErrorCode());
            }else if (NumberHandlerUtil.isEqual(status, DataStatusEnum.BAN.getType())){
                //项目禁用时不允许设备登录
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PROJECT_IS_BANNED.getErrorCode());
            }
            //判断设备状态
            Integer devStatus = iCloudIntercomServiceClient.getDeviceState(sn);
            if (devStatus == null){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
            }else if (devStatus != DataStatusEnum.NORMAL.getType()){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_BANNED.getErrorCode());
            }

            CloudIntercomDeviceVO result = iCloudIntercomServiceClient.cloudIntercomLogin(sn);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】设备云端登录认证失败", e);
        }
    }*/

    /**
     * <desc>
     * 设备端上电请求云端获取license与md5串
     * </desc>
     *
     * @param sn    设备序列号
     * @param token 登录token
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/20
     */
    @RequestMapping(value = "/device/getLicense", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO getLicense(String sn, String token) {
        //合法性判断
        if (StringUtils.isBlank(sn)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
        }
        MessageVO messageVO;
        try {
            /*DeviceCloudIntercomInfoPO cloud=iCloudIntercomServiceClient.getLicense(sn);
            if(cloud==null){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_ERROR.getErrorCode());
            }else if(StringUtils.isBlank(cloud.getLicense()) || StringUtils.isBlank(cloud.getMd5())){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_LICENSE_ERROR.getErrorCode());
            }*/
            Map<String, Object> map = new HashMap<>();
            map.put("license", "");
            map.put("md5", "");
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);

            /*LOG.info(String.format("【getLicense返回结果】 sn:%s，license：%s，md5：%s",
                    sn, cloud.getLicense(), cloud.getMd5()));*/

        } catch (Exception e) {
            throw new DataAccessException("【云对讲】设备端上电请求云端获取license与md5串失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     * 云端接收QQ与TinyID映射信息
     * </desc>
     *
     * @param sn           设备唯一码
     * @param din
     * @param qqTinyIdJson 映射信息列表json
     * @param token
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/20
     */
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_SAVE_QQ_TINYID)
    @RequestMapping(value = "/device/pushQQAndTinyId", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pushQQAndTinyId(String sn, String din, String qqTinyIdJson, String token) {
        //合法性判断
        if (StringUtils.isBlank(sn)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
        }
        if (StringUtils.isBlank(din)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DIN_IS_NULL.getErrorCode());
        }
        if (StringUtils.isBlank(qqTinyIdJson)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_QQANDTINY_IS_NULL.getErrorCode());
        }

        LOG.info(String.format("【pushQQAndTinyId请求参数】 sn:%s，din：%s，qqTinyIdJson：%s",
                sn, din, qqTinyIdJson));
        List<PropertyCloudQqTinyDTO> qqTinyDTOS;
        try {
            qqTinyDTOS = (List<PropertyCloudQqTinyDTO>) JsonUtil.toListObject(qqTinyIdJson, ArrayList.class, PropertyCloudQqTinyDTO.class);
        } catch (Exception e) {
            LOG.error("云对讲pushQQAndTinyId【云端接收QQ与TinyID映射信息】解析json失败");
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_QQANDTINY_ERROR.getErrorCode());
        }

        try {
            List<PropertyCloudQqTinyDTO> notFound = iCloudIntercomServiceClient.pushQQAndTinyId(sn, din, qqTinyDTOS);
            if (null != notFound && !notFound.isEmpty()) {
                LOG.info(String.format("【pushQQAndTinyId返回未注册列表】 sn:%s，din：%s，qqTinyIdJson(notFound)：%s",
                        sn, din, JSON.toJSONString(notFound)));
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_QQANDTINY_NOT_FOUND.getErrorCode(), notFound);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】保存QQ与TinyID映射信息失败", e);
        }
    }


    /**
     * <desc>
     *      云端接收设备端的通行记录
     * </desc>
     *
     * @param sn
     * @param type  记录类型 4表示电话呼叫，7表示设备上密码通行
     * @param deviceRecordJson json映射信息
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/21
     */
    /*@LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_DEVICE_RECORD)
    @RequestMapping(path = "/device/pushDeviceRecord",method = {RequestMethod.POST, RequestMethod.GET})
    public MessageVO pushDeviceRecord(String token ,String sn, Integer type, String deviceRecordJson){
        //合法性判断
        if(StringUtils.isBlank(sn)){
            return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
        }
        if(type == null){
            return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_RECORD_TYPE_IS_NULL.getErrorCode());
        }
        if(StringUtils.isBlank(deviceRecordJson)){
            return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_IS_NULL.getErrorCode());
        }
        LOG.info(String.format("【pushDeviceRecord请求参数】 sn:%s，type：%s，deviceRecordJson：%s",
                sn, type, deviceRecordJson));
        if (!NumberHandlerUtil.isEqual(type,4) && !NumberHandlerUtil.isEqual(type,7)){
            return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_TYPE_INVALID.getErrorCode());
        }
        if(type == 4) {//电话呼叫
            try {
                List<CloudTalkPhoneCallPassDTO> phones = (List<CloudTalkPhoneCallPassDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkPhoneCallPassDTO.class);
            } catch (Exception e) {
                LOG.error("云对讲pushDeviceRecord【云端接收设备端的通行记录】解析电话呼叫通行记录json失败", e);
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            }
        }
        if(type == 7) {//密码通行

            try {
                List<CloudTalkPwdPassDTO> pwd = (List<CloudTalkPwdPassDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkPwdPassDTO.class);
            } catch (Exception e) {
                LOG.error("云对讲pushDeviceRecord【云端接收设备端的通行记录】解析密码开门通行记录json失败", e);
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            }
        }

        try{
            Integer res = iCloudIntercomServiceClient.pushDeviceRecord(sn, type, deviceRecordJson);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】云端接收设备端的通行记录失败", e);
        }
    }*/

    /**
     * <desc>
     * 云端接收H5端上传的通行记录
     * </desc>
     *
     * @param sn               云对讲sn
     * @param type             2表示QQ呼叫 3表示用户本人通行
     * @param deviceRecordJson json数据
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/22
     */
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_PUSH_QQ_RECORD)
    @RequestMapping(path = "/device/pushQqRecord", method = RequestMethod.POST)
    public MessageVO pushQqRecord(String sn, Integer type, String deviceRecordJson, String token) {
        //合法性判断
        if (StringUtils.isBlank(sn)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
        }
        if (type == null) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_RECORD_TYPE_IS_NULL.getErrorCode());
        }
        if (StringUtils.isBlank(deviceRecordJson)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_IS_NULL.getErrorCode());
        }
        LOG.info(String.format("【pushQqRecord请求参数】 sn:%s，type：%s，deviceRecordJson：%s",
                sn, type, deviceRecordJson));

        if (!NumberHandlerUtil.isEqual(type, 2) && !NumberHandlerUtil.isEqual(type, 3)) {
            return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PASS_RECORD_TYPE_INVALID.getErrorCode());
        }
        if (type == 2) {//访客呼叫QQ记录
            try {
                List<CloudTalkQqDTO> qqs = (List<CloudTalkQqDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkQqDTO.class);
            } catch (Exception e) {
                LOG.error("云对讲pushQqRecord【云端接收H5端上传的通行记录】解析访客呼叫QQ记录json失败", e);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            }
        }
        if (type == 3) {//用户本人通行
            try {
                List<CloudTalkSelfDTO> selfs = (List<CloudTalkSelfDTO>) JsonUtil.toListObject(deviceRecordJson, ArrayList.class, CloudTalkSelfDTO.class);
            } catch (Exception e) {
                LOG.error("云对讲pushDeviceRecord【云端接收设备端的通行记录】解析密码开门通行记录json失败", e);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_PHONE_PASS_RECORD_ERROR.getErrorCode());
            }
        }

        try {
            Integer res = iCloudIntercomServiceClient.pushQqRecord(sn, type, deviceRecordJson);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】云端接收H5端上传的通行记录失败", e);
        }
    }


    /**
     * <desc>
     * 获取设备所有者的认证信息(全量)
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-16
     */
    @RequestMapping(value = "/device/pullDeviceAuthInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object pullDeviceAuthInfo(CloudIntercomDeviceAuthGetDTO getDTO, String token) {
        String elapsedtime = "【pullDeviceAuthInfo获取设备所有者的认证信息】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            //合法性判断
            if (null == getDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            elapsedtime += ";getDeviceServeRoomsByPage开始执行：" + DateUtil.fomatDate1(new Date());
            //获取服务的房间列表及其住户信息
            Page<CloudIntercomDeviceAuthVO.Room> roomPage =
                    iCloudIntercomServiceClient.getDeviceServeRoomsByPage(getDTO);

            elapsedtime += ";getUsersByRoomIds开始执行：" + DateUtil.fomatDate1(new Date());
            if (null != roomPage && roomPage.getRows() != null && roomPage.getRows().size() > 0) {
                List<String> roomIds = new ArrayList<>();
                for (int i = 0; i < roomPage.getRows().size(); i++) {
                    roomIds.add(roomPage.getRows().get(i).getRoomId());
                    //每50个房间获取一次
                    if (roomIds.size() == 50) {
                        List<CloudIntercomDeviceAuthVO.RoomUser> users =
                                iCloudIntercomServiceClient.getUsersByRoomIds(StringUtils.join(roomIds, ','), getDTO.getSn());
                        if (users != null && !users.isEmpty()) {
                            users.forEach(usr -> {
                                for (int j = 0; j < roomPage.getRows().size(); j++) {
                                    CloudIntercomDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                    //组装vip标识
                                    if (usr.getUserLabel() == null) {
                                        usr.setIsVip(0);
                                    } else {
                                        usr.setIsVip(Arrays.asList(usr.getUserLabel().split(",")).contains("1") ? 1 : 0);
                                    }


                                    if (room.getRoomId().equals(usr.getRoomId())) {
                                        if (room.getRoomUserArr() == null) {
                                            room.setRoomUserArr(new ArrayList<>());
                                            room.getRoomUserArr().add(usr);
                                        } else {
                                            room.getRoomUserArr().add(usr);
                                        }
                                    }
                                }
                            });
                        }
                        roomIds.clear();
                    }
                }
                if (!roomIds.isEmpty()) {
                    //1.通过设备查询到设备的所在单元和楼栋信信息
                    List<Map<String, String>> addressMap = iCloudIntercomServiceClient.getUnitIdByDeviceUnique(StringHandlerUtil.getDeviceUniqueBySn(getDTO.getSn()));
                   // LOG.info("====通过设备查询到设备的所在单元和楼栋信信息=====>{}",addressMap.toString());
                         //去除重复的电梯信息
                    Set<CloudElevatorVO> DeviceUniques = new HashSet<>();
                    for (Map<String, String> map : addressMap) {
                        //2.通过地址查询到该地址下的电梯信息集合（包含电梯的正背门信息），用于跟用户的设置的常用楼层的设备进行比较
                        List<CloudElevatorVO> deviceUniqueList= iCloudIntercomServiceClient.getElevatorLiftDoorTypeListByAddress(map);
                    //LOG.info("====通过地址查询到该地址下的电梯信息集合=====>{}",deviceUniqueList.toString());
                        for (CloudElevatorVO CloudElevator : deviceUniqueList) {
                            DeviceUniques.add(CloudElevator);
                        }
                    }
                  //  LOG.info("====去除重复的电梯集合=====>{}",DeviceUniques.toString());
                    List<CloudIntercomDeviceAuthVO.RoomUser> users =
                            iCloudIntercomServiceClient.getUsersByRoomIds(StringUtils.join(roomIds, ','), getDTO.getSn());
                    if (users != null && !users.isEmpty()) {
                        users.forEach(usr -> {
                            for (int j = 0; j < roomPage.getRows().size(); j++) {
                                CloudIntercomDeviceAuthVO.Room room = roomPage.getRows().get(j);
                                // 组装vip标识
                                if (usr.getUserLabel() == null) {
                                    usr.setIsVip(0);
                                } else {
                                    usr.setIsVip(Arrays.asList(usr.getUserLabel().split(",")).contains("1") ? 1 : 0);
                                }

                                //组装常用楼层和公共楼层
                                //1.得到用户所拥有的楼层机号对应关系
                                String commonFloor = StringHandlerUtil.getNullOrStringForObject(usr.getCommonFloor());
                                String publicFloor = StringHandlerUtil.getNullOrStringForObject(usr.getPublicFloor());
                                //2.获取当前云对讲的地址
//                              //3.获取当前地址的下的电梯 正背们和机号
                                //4.比对用户所用的常用楼层的对应的机号的楼层号
                                net.sf.json.JSONObject jsonCommonFloor = null;
                                net.sf.json.JSONObject jsonPublicFloor = null;
                                if (commonFloor != null) {
                                    jsonCommonFloor = net.sf.json.JSONObject.fromObject(commonFloor);
                                }
                                if (publicFloor != null) {
                                    jsonPublicFloor = net.sf.json.JSONObject.fromObject(publicFloor);
                                }

                                for (CloudElevatorVO cloudElevatorVO : DeviceUniques) {
                                    if (commonFloor == null) {
                                        if ("1".equals(cloudElevatorVO==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                //正门常用楼层
                                            usr.setFrontCommonFloor("");
                                        } else {
                                            usr.setBackCommonFloor("");
                                        }
                                    } else {
                                        if (jsonCommonFloor.containsKey(cloudElevatorVO.getDeviceUnique())) {
                                           // if ("1".equals(elevator==null?"":elevator.get("liftDoorType")+"")) {
                                           if ("1".equals(cloudElevatorVO.getLiftDoorType()==null?"":cloudElevatorVO.getLiftDoorType())) {

                                                    //正门常用楼层
                                                usr.setFrontCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                            } else {
                                                usr.setBackCommonFloor("x".equals(jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonCommonFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                            }
                                        }
                                    }
                                    if (publicFloor == null) {
                                        if ("1".equals(cloudElevatorVO==null?"":cloudElevatorVO.getLiftDoorType())) {
                                            //正门常用公共楼层
                                            usr.setFrontPublicFloor("");
                                        } else {
                                            usr.setBackPublicFloor("");
                                        }
                                    } else {
                                        if (jsonPublicFloor.containsKey(cloudElevatorVO.getDeviceUnique())) {
                                            if ("1".equals(cloudElevatorVO.getLiftDoorType()==null?"":cloudElevatorVO.getLiftDoorType())) {
                                                //正门常用公共楼层
                                                usr.setFrontPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                            } else {
                                                usr.setBackPublicFloor("x".equals(jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString())?"":jsonPublicFloor.get(cloudElevatorVO.getDeviceUnique()).toString());
                                            }
                                        }
                                    }

                                }
                                if (room.getRoomId().equals(usr.getRoomId())) {
                                    if (room.getRoomUserArr() == null) {
                                        room.setRoomUserArr(new ArrayList<>());
                                        room.getRoomUserArr().add(usr);
                                    } else {
                                        room.getRoomUserArr().add(usr);
                                    }
                                }

                            }
                        });
                    }
                }

            }
            CloudIntercomDeviceAuthVO deviceAuthVO = new CloudIntercomDeviceAuthVO();
            deviceAuthVO.setDeviceAuthArr(roomPage.getRows());
            deviceAuthVO.setCurrentTotal(roomPage.getRows().size());
            deviceAuthVO.setTotal(roomPage.getPage().getTotalNumber());
            deviceAuthVO.setPage(roomPage.getPage().getCurrentPage());
            deviceAuthVO.setHaveNext(roomPage.getPage().getTotalPage() -
                    roomPage.getPage().getCurrentPage() > 0 ? 1 : 0);

            //最后一页并且需要访客信息的时候
            if (deviceAuthVO.getHaveNext() == 0) {
                //获取云对讲设备信息
                CloudIntercomDeviceCacheVO cacheVO = iCloudIntercomServiceClient.retrieve(token);
                //拼接访客信息
                List<CloudIntercomDeviceAuthVO.Room> deviceAuthArr = roomPage.getRows();
                //查询该设备访客下的信息
                List<CloudIntercomVisitorVO> list = iCloudIntercomServiceClient.getVisitorInfoByUnique(cacheVO.getDeviceUnique(), cacheVO.getSmartType());
                for (CloudIntercomVisitorVO vo : list) {
                    CloudIntercomDeviceAuthVO.Room room = new CloudIntercomDeviceAuthVO.Room();
                    CloudIntercomDeviceAuthVO.RoomUser roomUser = new CloudIntercomDeviceAuthVO.RoomUser();
                    List<CloudIntercomDeviceAuthVO.RoomUser> listRoomUser = new ArrayList<>();
                    roomUser.setUserId(vo.getVFaceId());
                    roomUser.setHouseUserType(0);
                    roomUser.setStartTime(vo.getStartTime());
                    roomUser.setEndTime(vo.getEndTime());
                    roomUser.setFacePicUrl(vo.getFacePicUrl());
                    roomUser.setRoomId(vo.getRoomId());
                    roomUser.setIdcardKey(vo.getIdcardKey());
                    room.setRoomId(vo.getRoomId());

                    listRoomUser.add(roomUser);
                    room.setRoomUserArr(listRoomUser);
                    deviceAuthArr.add(room);
                }
            }
       /*     LOG.info(String.format("【pullDeviceAuthInfo返回数据】 sn:%s，deviceAuth：%s",
                    getDTO.getSn(), JSON.toJSONString(deviceAuthVO)));*/
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceAuthVO);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取设备所有者的认证信息失败", e);
        } finally {
            elapsedtime += ";【pullDeviceAuthInfo获取设备所有者的认证信息】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     *     获取物业公共信息—文字公告
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    /*@RequestMapping(value = "/device/pullPropertyOfText", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullPropertyOfText(CloudIntercomMediaGetDTO getDTO){
        try {
            //合法性判断
            if (null == getDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            getDTO.setMediaType(MediaTypeEnum.TEXT.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("textMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】获取文字公共信息失败", e);
        }
    }*/

    /**
     * <desc>
     *     获取物业公共信息—图片
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    /*@RequestMapping(value = "/device/pullPropertyOfPic", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullPropertyOfPic(CloudIntercomMediaGetDTO getDTO){
        try {
            //合法性判断
            if (null == getDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            getDTO.setMediaType(MediaTypeEnum.IMGAE.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("picMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】获取图片公共信息失败", e);
        }
    }*/

    /**
     * <desc>
     *     获取物业公共信息—视频
     * <desc/>
     *
     * @param getDTO
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    /*@RequestMapping(value = "/device/pullPropertyOfVideo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullPropertyOfVideo(CloudIntercomMediaGetDTO getDTO){
        try {
            //合法性判断
            if (null == getDTO){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            getDTO.setMediaType(MediaTypeEnum.VIDEO.getType().toString());
            List<CloudIntercomMediaVO> mediaVOS = iCloudIntercomServiceClient.getDeviceMedias(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("videoMediaInfoArr", mediaVOS);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】获取视频公共信息失败", e);
        }
    }*/

    /**
     * <desc>
     * 获取设备工程密码
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @RequestMapping(value = "/device/pullDevicePwd", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullDevicePwd(String sn, String token) {
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            //获取云对讲设备信息
            CloudIntercomDeviceCacheVO cacheVO = iCloudIntercomServiceClient.retrieve(token);
            if (null == cacheVO) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_LOGIN_ERROE.getErrorCode());
            }

            CloudIntercomOtherInfoVO otherInfoVO =
                    iCloudIntercomServiceClient.getDeviceOtherInfo(cacheVO.getDeviceUnique());

            Map<String, Object> map = new HashMap<>();
            map.put("engineerPwd", otherInfoVO.getEngineerPwd());

            //LOG.info(String.format("【pullDevicePwd工程密码-返回数据】 sn:%s，engineerPwd：%s", sn, otherInfoVO.getEngineerPwd()));
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取设备工程密码失败", e);
        }
    }

    /**
     * <desc>
     * 获取设备附加信息
     * <desc/>
     *
     * @param sn
     * @param type 附加信息类型：1工程密码，2项目名称（小区名称），3设备自身附加信息，4对讲与监视时长变更，5root账号密码和端口，6出局码
     *             多个类型以英文逗号分隔
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-20
     */
    @RequestMapping(value = "/device/pullChangeInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullChangeInfo(String sn, String type, String token) {
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(type)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_ADDITIONAL_INFO_TYPE_IS_NULL.getErrorCode());
            }

            //获取云对讲设备信息
            CloudIntercomDeviceCacheVO cacheVO = iCloudIntercomServiceClient.retrieve(token);
            if (null == cacheVO) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_LOGIN_ERROE.getErrorCode());
            }

            CloudIntercomOtherInfoVO otherInfoVO =
                    iCloudIntercomServiceClient.getDeviceOtherInfo(cacheVO.getDeviceUnique());

            Map<String, Object> map = new HashMap<>();
            if (type.contains("1")) {
                map.put("engineerPwd", otherInfoVO.getEngineerPwd());
            }
            if (type.contains("2")) {
                map.put("projectName", otherInfoVO.getProjectName());
            }
            if (type.contains("3")) {
                map.put("deviceName", otherInfoVO.getDeviceName());
            }
            if (type.contains("4")) {
                map.put("watchLimit", otherInfoVO.getWatchLimit());
                map.put("talkLimit", otherInfoVO.getTalkLimit());
            }
            if (type.contains("5")) {
                map.put("rootPwd", otherInfoVO.getRootPwd());
                map.put("rootPort", otherInfoVO.getRootPort());
            }
            if (type.contains("6")) {
                map.put("outCode", otherInfoVO.getOutCode());
            }

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取设备附加信息失败", e);
        }
    }


    /**
     * <desc>
     *      云对讲获取待轮询命令
     * <desc/>
     *
     * @param getDTO 分页获取
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    /*@RequestMapping(value = "/device/pullChangeLog", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pullChangeLog(CloudIntercomChangeLogGetDTO getDTO){
        String elapsedtime = "【pullChangeLog获取待轮询命令】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            //合法性判断
            if (null == getDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(getDTO.getSn())){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (!NumberHandlerUtil.isGreaterThan(iCloudIntercomServiceClient.checkSnExist(getDTO.getSn()), 0)){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_NOT_EXIST.getErrorCode());
            }
            if (getDTO.getPage() == null){
                getDTO.setPage(1);
            }
            if (getDTO.getPageSize() == null){
                getDTO.setPageSize(20);
            }

            elapsedtime += ";getDeviceChangeLogOrders开始执行：" + DateUtil.fomatDate1(new Date());
            Page<CloudIntercomChangeLogOrderVO> page =
                    iCloudIntercomServiceClient.getDeviceChangeLogOrders(getDTO);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("total", page.getPage().getTotalNumber());
            resultMap.put("page", page.getPage().getCurrentPage());
            resultMap.put("currentTotal", page.getRows().size());
            resultMap.put("haveNext", page.getPage().getTotalPage() - page.getPage().getCurrentPage() > 0 ? 1: 0);
            resultMap.put("commandArr", page.getRows());

            //输出响应的commandId
            String commandIds = "";
            if (page.getRows() != null && !page.getRows().isEmpty()){
                for (CloudIntercomChangeLogOrderVO orderVO : page.getRows()){
                    commandIds += orderVO.getId() + ',';
                }
            }
            //LOG.info(String.format("【pullChangeLog轮询命令返回】 sn:%s，commandId：%s", getDTO.getSn(), StringHandlerUtil.trim(commandIds, ",")));

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】获取轮询命令失败", e);
        }finally {
            elapsedtime += ";【pullChangeLog获取待轮询命令】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }*/

    /**
     * <desc>
     *      设备端轮询结果通知云端
     * <desc/>
     *
     * @param
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    /*@RequestMapping(value = "/device/reportChangeLog", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO reportChangeLog(String sn, String id){
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(id)){
                return new MessageVO(CloudIntercomErrorCodeEnum.CLOUD_CHANGE_LOG_ORDER_ID_IS_NULL.getErrorCode());
            }

            Integer res = iCloudIntercomServiceClient.finishChangeLogOrders(sn, id);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), res);
        }catch (Exception e){
            throw new DataAccessException("【云对讲】设备端轮询结果通知云端失败", e);
        }
    }*/


    /**
     * <desc>
     * 获取云对讲设备使用状态
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-23
     */
    @RequestMapping(value = "/device/getState", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO getState(String sn) {
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            Integer state = iCloudIntercomServiceClient.getDeviceState(sn);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("state", state);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】查询设备使用状态失败", e);
        }
    }

    /**
     * <desc>
     * 获取云对讲设备二维码
     * <desc/>
     *
     * @param sn
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-23
     */
    @RequestMapping(value = "/device/downDeviceQrcode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO downDeviceQrcode(String sn) {
        try {
            //合法性判断
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }

            //TODO 目前云对接未接入QQ物联，二维码返回为空即可-2018.1.29
            String qrcode = "";
            //String qrcode = iCloudIntercomServiceClient.getDeviceQrcodeUrl(sn);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("deviceQrcodeUrl", qrcode);

            //LOG.info(String.format("【downDeviceQrcode获取云对讲设备二维码-返回数据】 sn:%s，deviceQrcodeUrl：%s", sn, qrcode));
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), resultMap);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取设备二维码失败", e);
        }
    }

    /**
     * <desc>
     * 云对讲推送强提醒消息
     * <desc/>
     *
     * @param
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-25
     */
    @LoggerInfo(operateDesc = LogDescConstant.CLOUD_INTERCOM_PUSH_TO_PHONE)
    @RequestMapping(value = "/device/pushToPhone", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO pushToPhone(CloudIntercomDevicePushInfoDTO infoDTO) {
        String elapsedtime = "【pushToPhone推送强提醒】开始执行：" + DateUtil.fomatDate1(new Date());
        try {
            //合法性判断
            if (null == infoDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(infoDTO.getSn())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(infoDTO.getDevSip()) || StringUtils.isBlank(infoDTO.getUserSip())) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_TO_PHONE_SIP_IS_NULL.getErrorCode());
            }
            LOG.info(String.format("【pushToPhone推送强提醒-请求参数】 sn:%s，devSip：%s，userSip:%s",
                    infoDTO.getSn(), infoDTO.getDevSip(), infoDTO.getUserSip()));

            elapsedtime += ";retrieve开始执行：" + DateUtil.fomatDate1(new Date());
            //获取云对讲设备信息
            CloudIntercomDeviceCacheVO cacheVO = iCloudIntercomServiceClient.retrieve(infoDTO.getToken());
            if (null == cacheVO) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_LOGIN_ERROE.getErrorCode());
            }

            elapsedtime += ";getPhoneNoByUserSips开始执行：" + DateUtil.fomatDate1(new Date());
            //根据userSip获取用户手机号
            List<String> phoneNos = iCloudIntercomServiceClient.getPhoneNoByUserSips(
                    cacheVO.getProjectId(),
                    infoDTO.getUserSip()
            );
            if (null == phoneNos || phoneNos.isEmpty()) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_USER_SIP_NOT_FIND.getErrorCode());
            }

            elapsedtime += ";getByDeviceUnique开始执行：" + DateUtil.fomatDate1(new Date());
            //获取设备名称
            String devName = "";
            PropertyEquipGetVO dev = iPropertyEquipServiceClient.getByDeviceUnique(cacheVO.getDeviceUnique());
            if (dev != null) {
                devName = dev.getDeviceName();
            }

            elapsedtime += ";pushWithByPhoneTag开始执行" + DateUtil.fomatDate1(new Date());
            String msg = String.format("{%s}正在呼入...", devName);
            List<String> pushPhones = new ArrayList<>();
            for (String phoneNo : phoneNos) {
                boolean pushRes = iIotTpJPushClientServiceClient.pushWithByPhoneTag(
                        msg,
                        phoneNo,
                        infoDTO.getDevSip(),
                        ""
                );
                if (pushRes) {
                    pushPhones.add(phoneNo);
                }
            }

            if (pushPhones.isEmpty()) {//推送失败
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PUSH_TO_PHONE_ALL_FAILED.getErrorCode());
            }
            String success = StringUtils.join(pushPhones, ",");
            phoneNos.removeAll(pushPhones);
            String failed = StringUtils.join(phoneNos, ",");

            LOG.info(String.format("【pushToPhone推送强提醒-返回】 sn:%s，pushSuccess：%s，pushFailed：%s",
                    infoDTO.getSn(), success, failed));

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),
                    "信息已成功推送给" + success + "手机用户");

        } catch (Exception e) {
            throw new DataAccessException("【云对讲】推送强提醒消息失败", e);
        } finally {
            elapsedtime += ";【pushToPhone推送强提醒】执行结束：" + DateUtil.fomatDate1(new Date());
            LOG.info(elapsedtime);
        }
    }

    /**
     * <desc>
     * 云端响应H5端鉴定权限
     * <desc/>
     *
     * @param sn
     * @param tinyId qq物联id
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-27
     */
    @RequestMapping(value = "/device/checkUser", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public MessageVO checkUser(String sn, String tinyId) {
        try {
            //合法性检测
            if (StringUtils.isBlank(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(tinyId)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TINY_ID_IS_NULL.getErrorCode());
            }

            boolean result = iCloudIntercomServiceClient.checkUserByTinyId(sn, tinyId);
            if (result) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            } else {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TINY_ID_USER_NO_PERMISSION.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】检测H5端用户权限失败", e);
        }
    }

    /**
     * <desc>
     * 设备主动获取待机界面图片
     * <desc/>
     *
     * @param sn
     * @return
     * @author Juguang.S
     * @createDate 2018-08-09
     */
    @PostMapping(path = "/device/pullStandbyInterfacePicture")
    @ResponseBody
    public MessageVO getStandbyInterfacePicture(String sn) {
        try {
            if (StringUtils.isEmpty(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            String standbyInterfaceUrl = iCloudIntercomServiceClient.getStandbyInterfacePicture(sn);
            Map<String, String> map = new HashMap<>();
            map.put("standbyInterfaceUrl", standbyInterfaceUrl);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】设备主动获取待机界面图片失败", e);
        }

    }

    /**
     * <desc>
     * 云对讲上报设备的能力集信息
     * </desc>
     *
     * @param token
     * @param capacitySet 表示设备支持哪些功能，有哪些能力 json String数据
     * @return
     * @author Juguang.S
     * @createDate 2018-08-09
     */
    @RequestMapping(path = "/device/reportCapacitySet")
    @ResponseBody
    public Object reportCapacitySet(String token, String capacitySet, String sn, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                capacitySet = StringHandlerUtil.getNullOrStringForObject(params.get("capacitySet"));
            }
            if (StringUtils.isBlank(capacitySet) || StringUtils.isBlank(sn)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iCloudIntercomServiceClient.reportCapacitySet(capacitySet, sn);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【云电梯】上报设备的能力集信息失败", e);
        }
    }

    /**
     * <desc>
     * 获取楼栋单元呼叫代号
     * <desc/>
     *
     * @param sn
     * @return
     * @author Jiaqi.X
     * @createDate 2018/11/27
     */
    @RequestMapping(path = "/device/getUnitAlias")
    @ResponseBody
    public MessageVO getUnitAlias(String sn) {
        try {
            if (StringUtils.isEmpty(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            List<Map<String, Object>> unitAlias = iCloudIntercomServiceClient.getUnitAlias(sn);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), unitAlias);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】获取楼栋单元呼叫代号", e);
        }

    }

    /**
     * <desc>
     * 通过百度指纹码绑定百度识别码来完成离线人脸识别
     * <desc/>
     *
     * @param sn
     * @param type    预留扩展字段 1=在线  2=离线   默认为1
     * @param baiduId 百度指纹码
     * @return
     * @author Juguang.S
     * @createDate 2019/02/26
     */
    @RequestMapping(path = "/device/bingBaiduCode")
    @ResponseBody
    public MessageVO bingBaiduCode(String token, String sn, String type, String baiduId, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                sn = params.get("sn").toString();
                type = params.get("type").toString();
                baiduId = params.get("baiduId").toString();
            }
            if (StringUtils.isEmpty(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            if (StringUtils.isEmpty(baiduId)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_BAIDUID_IS_NULL.getErrorCode());
            }
            //如果该baiduId是初次绑定则需校验该设备是否已购买
            String deviceUnique = String.format("%s%s%04d", sn.substring(0, 8), 3, Integer.parseInt(sn.substring(sn.length() - 3, sn.length())));
            //校验该云对讲机号有没被其它已激活的设备占用
            if (iAppPadFaceServiceClient.isDeviceIdUserd(baiduId, deviceUnique) > 0) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TALK_DEVICEID_IS_USERD.getErrorCode());
            }
            Integer bingStatus = iCloudIntercomServiceClient.getBaiduIdBingStatus(baiduId);
            //根据deviceUnique查询该设备是否已绑定或已购买
            Integer buyOrBingStatus = iCloudIntercomServiceClient.getDeviceBuyOrBingStatus(deviceUnique);
            if (bingStatus == 0 && buyOrBingStatus == 0) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_BAIDUCODE_IS_NOT_BUY.getErrorCode());
            }
            String baiduCode = iCloudIntercomServiceClient.getBaiduCode(sn, baiduId);
            if (StringUtils.isEmpty(baiduCode)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_BAIDUCODE_IS_EMPTY.getErrorCode());
            }
            Map<String, String> map = new HashMap<>();
            map.put("baiduCode", baiduCode);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲】通过百度指纹码绑定百度识别码失败", e);
        }

    }

    /**
     * <desc>
     * 用户读取欠费消息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2019/05/31
     */
    @RequestMapping(path = "/getArrearageInfo", method = RequestMethod.POST)
    @ResponseBody
    public MessageVO getArrearageInfo(String token, String sn, String roomId, String userId, String type, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(token)) {
                Map<String, Object> params = request.getAttribute("params") != null ? (HashMap) request.getAttribute("params") : null;
                token = params.get("token").toString();
                sn = params.get("sn").toString();
                type = params.get("type").toString();
                roomId = params.get("roomId").toString();
                userId = params.get("userId").toString();
            }

            if (StringUtils.isEmpty(sn)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_SN_IS_NULL.getErrorCode());
            }
            String projectId = sn.substring(0, 8);
            String deviceId = String.format("0%s", sn.substring(sn.length() - 3, sn.length()));
            String qrCodeUrl = H5_PAYMENT_HTML + "?project" +
                    "Id=" + projectId + "&userId=" + userId + "&roomId=" + roomId + "&deviceType=3" + "&deviceId=" + deviceId;
            Map<String, String> data = iAppDeviceServiceClient.getArrearageInfo(projectId, roomId, null, userId, type, "3");
            if (data != null && !data.isEmpty()) {
                data.put("QRCode", qrCodeUrl);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【App_getArrearageInfo】用户读取欠费消息失败", e);
        }
    }

    /**
     * <desc>
     * 云对讲设备获取白名单授权文件
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-08-12 15:21
     * @Param password 获取白名单授权文件密码   mac 获取对应授权文件的设备的MAC地址
     * @Return
     * @Exception
     */
    @UnAuthAccessRequired
    @PostMapping("/device/getWhiteListAuthFile")
    @ResponseBody
    public Object getWhiteListAuthFile(String password, String mac, HttpServletRequest request) {
        try {
            Date nowTime = new Date();
            if (StringUtils.isBlank(password)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(mac)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode());
            }
            //1判断设备mac地址是否在白名单中
            OperateDeviceWhiteListVO whiteListByMac = deviceWhiteListServiceClient.getWhiteListByMac(mac);
            if (whiteListByMac == null) {
                //1.如果白名单里面确实没有这个mac设备，新增白名单记录为设备异常标记为2 ，做新增白名单记录 ，exception_flag为2：异常
                OperateDeviceWhiteListDTO whiteListDTO = new OperateDeviceWhiteListDTO();
                whiteListDTO.setExceptionFlag(2);
                whiteListDTO.setChangeFlag(2);
                whiteListDTO.setMacAddress(mac);
                whiteListDTO.setLastUploadTime(nowTime);
                whiteListDTO.setRequestTimes(1);
                deviceWhiteListServiceClient.save(whiteListDTO);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            if (whiteListByMac != null && "2".equals(whiteListByMac.getChangeFlag())) {
                //2.如果白名单里面有这个Mac的记录，但是change_flag为2：未转换
                OperateDeviceWhiteListDTO whiteListDTO = new OperateDeviceWhiteListDTO();
                whiteListDTO.setWhiteListId(whiteListByMac.getWhiteListId());
                whiteListDTO.setRequestTimes(whiteListByMac.getRequestTimes() + 1);
                whiteListDTO.setLastUploadTime(nowTime);
                deviceWhiteListServiceClient.update(whiteListDTO);
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            if (whiteListByMac != null) {
                if ("1".equals(whiteListByMac.getActivateStatus()) && DataStatusEnum.BAN.getType().equals(whiteListByMac.getStatus())) {
                    ErrorCode errorCode = CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_ERROR.getErrorCode();
                    return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_ERROR.getErrorCode(), String.format(errorCode.getCodeMsg(), mac));
                }
            }
            //获取授权规则信息
            OperateDeviceWhiteListAuthRulesDTO rulesDTO = new OperateDeviceWhiteListAuthRulesDTO();
            rulesDTO.setPassword(Base64.encode(DesEncryptUtil.Encrypt(URLEncoder.encode(new String(password.getBytes()), "utf-8").getBytes(), PlatformConstants.OPERATE_USER_PASSWORD_KEY)));
            //通过输入的授权密码查询授权规则信息  得到 授权文件次数 授权文件的有效时间 授权文件逻辑id
            //2.校验授权文件密码是否输入正确
            List<OperateDeviceWhiteListAuthRulesVO> rules =
                    iOperateDeviceWhiteListAuthRulesServiceClient.getWhiteListAuthRulesByList(rulesDTO);
            if (rules.size() == 0) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_ERROR.getErrorCode());
            }
            String ruleId = null;
            //3.校验获取的设备授权文件规则密码的有效时间
            List<Object> flagList = new ArrayList<>();
            for (OperateDeviceWhiteListAuthRulesVO rule : rules) {
                Date newdate = new Date();//获取激活文件时间
                String beginDateTime = rule.getStartTime();//预先设置好的授权文件有效的开始时间
                String endDateTime = rule.getEndTime();//预先设置好的授权文件有效的结束时间
                boolean flag = DateUtil.getTimeQuantum("yyyy-MM-dd HH:mm:ss", newdate, beginDateTime, endDateTime);
                // 当校验的是获取文件时间在有效期内得到它的规则id，拿出来传给前端，方便后面更新规则表的信息
                // 当校验的是获取文件时间在有效期内并且可用次数和已使用次数不相等，得到它的规则id，拿出来传给前端，方便后面更新规则表的信息
                if (flag && !rule.getAmount().equals(rule.getUsedTimes())) {
                    ruleId = rule.getRuleId();
                }
                flagList.add(flag);
            }
            //判断获取文件的时间是否在授权文件的有效期内
            if (!flagList.contains(true)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TIME_IS_ERROR.getErrorCode());
            }
            //判断授权文件规则密码次数
            if (ruleId == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_TIMES_IS_NULL.getErrorCode());
            }
            //4.判断授权文件的剩余次数是否小于等于设置的次数
            OperateDeviceAuthFileDTO deviceAuthFileDTO = new OperateDeviceAuthFileDTO();
            DeviceAuthFileVO effectiveAuthFile = iOperateDeviceWhiteListAuthFileServiceClient.getEffectiveAuthFile(deviceAuthFileDTO);
            if (effectiveAuthFile == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_FILE_IS_NULL.getErrorCode());
            }


            Map<String, String> data = new HashMap<>();
            data.put("authFileUrl", effectiveAuthFile.getAuthFileUrl());
            data.put("authId", effectiveAuthFile.getAuthId());
            data.put("ruleId", ruleId);
            data.put("consumeFileName", effectiveAuthFile.getFileName());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);

        } catch (Exception e) {
            throw new DataAccessException("【Equip_getWhiteListAuthFile】 云对讲设备用户获取授权文件失败", e);
        }
    }


    /**
     * <desc>
     * 云对讲设备上传设备的激活状态
     * </desc>
     *
     * @Author chengshican
     * @Date 2020-08-12 15:34
     * @Param deviceType 设备类型 1人脸识别云对讲门禁 2人脸识别仪  3一体式人脸识别门禁
     * @Param time 激活时间
     * @Param mac 设备的Mac地址
     * @Param activationmMsg 激活的文件新
     * @Param ruleId  授权文件的规则id
     * @Param authId  授权文件的id
     * @Return consumeFileName 授权文件名称
     * @Exception
     */

    @UnAuthAccessRequired
    @PostMapping("/device/uploadActivateStatus")
    @ResponseBody
    public Object uploadActivateStatus(String deviceType, String time, String mac, String ruleId, String authId, String consumeFileName, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(deviceType)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_PASSWORD_IS_NULL.getErrorCode());
            }
            if (StringUtils.isBlank(mac)) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_MAC_IS_NULL.getErrorCode());
            }
            //1判断设备mac地址是否在白名单中
            OperateDeviceWhiteListVO whiteListByMac = deviceWhiteListServiceClient.getWhiteListByMac(mac);
            if (whiteListByMac == null) {
                return new MessageVO(CloudDeviceErrorCodeEnum.CLOUD_DEVICE_MAC_IS_NULL.getErrorCode());
            }
            //保存授权文件消息信息表
            OperateDeviceWhiteListAuthFileConsumeRecordsDTO consumeRecordsDTO = new OperateDeviceWhiteListAuthFileConsumeRecordsDTO();
            consumeRecordsDTO.setConsumeNum(1);
            consumeRecordsDTO.setDeviceActivateTime(time);
            consumeRecordsDTO.setDeviceMac(mac);
            consumeRecordsDTO.setConsumeFileName(consumeFileName);
            consumeRecordsDTO.setDeviceType(Integer.parseInt(deviceType));
            consumeRecordsDTO.setAuthId(authId);
            consumeRecordsDTO.setRuleId(ruleId);
            authFileConsumeRecordsServiceClient.save(consumeRecordsDTO);


            //更新白名单设备信息
            OperateDeviceWhiteListDTO operateDeviceWhiteListDTO = new OperateDeviceWhiteListDTO();
            operateDeviceWhiteListDTO.setAuthId(authId);
            operateDeviceWhiteListDTO.setDeviceType(Integer.parseInt(deviceType));
            operateDeviceWhiteListDTO.setMacAddress(mac);
            operateDeviceWhiteListDTO.setActivateTime(time);
            operateDeviceWhiteListDTO.setAuthFileName(consumeFileName);
            deviceWhiteListServiceClient.updateStatusByAuthIdAndMAC(operateDeviceWhiteListDTO);
            //更新授权文件信息
            OperateDeviceAuthFileDTO operateDeviceAuthFileDTO = new OperateDeviceAuthFileDTO();
            operateDeviceAuthFileDTO.setAuthId(authId);
            operateDeviceAuthFileDTO.setUsedTimes("1");
            operateDeviceAuthFileDTO.setEffectiveTimes("1");
            iOperateDeviceWhiteListAuthFileServiceClient.updateAuthFileByAuthId(operateDeviceAuthFileDTO);
            //更新授权文件规则信息
            OperateDeviceWhiteListAuthRulesDTO authRulesDTO = new OperateDeviceWhiteListAuthRulesDTO();
            authRulesDTO.setRuleId(ruleId);
            authRulesDTO.setUsedTimes(1);
            iOperateDeviceWhiteListAuthRulesServiceClient.updateWhiteListAuthRulesByRuleId(authRulesDTO);


            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());

        } catch (Exception e) {
            throw new DataAccessException("【Equip_uploadActivateStatus】 云对讲设备用户上传设备的激活状态失败", e);
        }
    }

}
